<template>
	<view>
		<view class="text-grey text-lg">
			<view class="action margin-bottom-sm flex justify-between" @click="tapSensor(sensor)">
				<view>
					<text class="cuIcon-titles text-green"></text>
					<text
						class="text-bold margin-right-sm">{{formatSensorType(sensor.type)}}{{$t('port')}}:{{sensor.port}}</text>
					<text v-if="sensor.sensorName">| {{sensor.sensorName}}</text>
				</view>
				<text class="cuIcon-right text-black text-xl margin-top-xs" style="float: right;"></text>
			</view>

			<view v-if="historyModalVisible">
				<view class="cu-bar">
					<view class="action text-green">{{explainChart.name}}</view>
					<button :style="{'--color': themeConfig.primaryColor}" class=" cu-btn shadow" @tap="hideModal">
						<view class="cuIcon-close"></view>
					</button>
				</view>
				<view class="margin-bottom-lg" v-if="historyModalVisible">
					<line v-if="explainChart.showType === 'echarts'" :dataList="explainChart.dataList" height="500rpx" />
					<view v-else style="height: 500rpx;overflow-y: auto">
						<view class="cu-list menu sm-bordercard-menu margin-top"
							style="margin-left: 40px;margin-right: 40px;">
							<view class="cu-item" v-for="(val,valIndex) in explainChart.dataList" :key="valIndex">
								<view class="content">
									{{val.val}}
								</view>
								<view class="action">
									{{val.time}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else
				style="display: grid;grid-template-columns:1fr 1fr;grid-template-rows 1fr 1fr;grid-auto-flow : row dense;grid-column-gap: 5px;">
				<view v-for="(item,index) in sensor.explainList" :key="index"
					:style="(item.isFullLine ? 'grid-column-start: span 2':'grid-column-start: span 1')">
					<view :style="{'background': item.background}"
						class="bg-white padding-sm margin-bottom-sm common-box">
						<view class="flex justify-between" @tap="getExplainWarnList(item)">
							<view class="flex justify-start margin-bottom">
								<view class="cu-avatar radius sm" :style="[{backgroundImage:`url(${item.iconUrl})`}]"
									style="width: 55rpx;height: 55rpx;background-color:rgba(0,0,0,0);margin: 5rpx 8rpx 0 0;">
								</view>
								<view>
									<view class="text-sm text-bold text-grey text-left">
										<text v-if="item.remark && item.remark!==''">
											{{item.remark}}
										</text>
										<text v-else>
											{{item.name}}
										</text>
									</view>
									<view class="text-gray text-xs">
										<text v-if="item.warnNum > 0"
											class="cuIcon-infofill text-red"></text>
										{{formatDateTime(item.valueDate)}}
									</view>
								</view>
							</view>
							<view style="float: right;" class="cuIcon-moreandroid"></view>
						</view>
						<view :style="[{color:themeConfig.primaryColor}]"
						class="margin-bottom"
							style="display: flex;justify-content: center;flex-wrap: wrap;min-height: 20px;"
							@tap="getExplainDataList(item)">
							<view class="text-xxl">
								<text v-for="(value,valueIndex) in formatValue(item)" :key="valueIndex" class="margin-right-xs">{{value}}</text>
								<text class="text-grey">{{item.unit}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="[isShowWarnListModel?'show':'']" style="text-align: start">
			<view class="cu-dialog bg-white" style="border-top-left-radius:20rpx;border-top-right-radius:20rpx;">
				<view class="cu-bar bg-white text-bold">
					<view class='action'>
						{{$t('warn')}}
					</view>
					<view class='action padding-right' style="font-size: 40rpx;"
						:style="[{color:themeConfig.primaryColor}]">
						<text v-if="!isShowCheck" class="cuIcon-add margin-right" @tap="showAddWarnModel"></text>
						<text v-if="explainWarnList.length != 0 && !isShowCheck" class="cuIcon-delete margin-right"
							@tap="showCheck()"></text>
						<text class="cuIcon-close margin-right" @tap="unShowExplainWarn()"></text>
					</view>
				</view>
				<view v-if="explainWarnList.length != 0">
					<view class="ztnCustom-cur flex">
						<view class="margin-xs text-center" style="width: 20%;" v-if="isShowCheck">
							<view>{{$t('select')}}</view>
						</view>
						<view class="margin-xs text-center" style="width: 20%;">{{$t('less')}}</view>
						<view class="margin-xs text-center" style="width: 20%;">{{$t('greater')}}</view>
						<view class="margin-xs text-center" style="width: 20%;">{{$t('equal')}}</view>
						<view class="margin-xs text-center" style="width: 20%;">{{$t('wave')}}</view>
						<view v-if="!isShowCheck" class="margin-xs text-center" style="width: 20%;"></view>
					</view>
					<scroll-view scroll-y="true" style="height:250px">
						<view>
							<checkbox-group @change="changeCheck">
								<view v-for="(item,index) in explainWarnList" :key="index" class="flex margin-bottom">
									<view class="margin-xs text-center" style="width: 20%;" v-if="isShowCheck">
										<checkbox class="round" :value="index" :checked="item.checked" />
									</view>
									<view class="margin-xs text-center" style="width: 20%;line-height: 20px;">
										{{item.less}}
									</view>
									<view class="margin-xs text-center" style="width: 20%;line-height: 20px;">
										{{item.greater}}
									</view>
									<view class="margin-xs text-center" style="width: 20%;line-height: 20px;">
										{{item.equal}}
									</view>
									<view class="margin-xs text-center" style="width: 20%;line-height: 20px;">
										{{item.wave}}
									</view>
									<button v-if="!isShowCheck" class="cu-btn block margin-tb-xs" size="mini"
										:style="{backgroundColor:themeConfig.primaryColor}"
										style="width: 20%;color: #fff;" hover-class="btn-hover-class" form-type="submit"
										@tap="editExplainWarn(item)">
										<text class="cuIcon-edit text-white"></text>
									</button>
								</view>
							</checkbox-group>
						</view>

					</scroll-view>
				</view>
				<view v-else class="text-center" style="margin-top:20px;margin-bottom: 20px;">
					<view class="cuIcon-edit text-grey" style="font-size:80px"></view>
					<button :style="{backgroundColor:themeConfig.primaryColor}" style="color: #fff;"
						class="cu-btn round line-grey margin lg" @tap="showAddWarnModel">{{$t('add')}}</button>
				</view>

				<view v-if="explainWarnList.length != 0">
					<view v-if="isShowCheck" class="flex justify-between align-center">
						<button class="cu-btn block line-grey margin lg"
							@tap="deleteExplainWarn">{{$t('delete')}}</button>
						<button class="cu-btn block line-grey margin lg"
							@tap="cancelExplainWarn">{{$t('cancel')}}</button>
					</view>
					<view v-else class="flex justify-between align-center">
						<button class="cu-btn block line-grey margin lg" @tap="saveExplainWarn">{{$t('save')}}</button>
						<button class="cu-btn block line-grey margin lg"
							@tap="cancelExplainWarn">{{$t('cancel')}}</button>
					</view>
				</view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="[isShowEditWarnModel?'show':'']" style="text-align: start">
			<view class="cu-dialog bg-white" style="border-top-left-radius:20rpx;border-top-right-radius:20rpx;">
				<view class="cu-bar bg-white text-bold">
					<view class='action'>
						{{$t('warn')}}
					</view>
				</view>
				<form @submit="addOrUpdateExplainWarn">
					<view class="cu-form-group">
						<view class="title">{{$t('less')}}</view>
						<input type="digit" v-model="explainWarn.less" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('greater')}}</view>
						<input type="digit" v-model="explainWarn.greater" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('equal')}}</view>
						<input v-model="explainWarn.equal" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('different')}}</view>
						<input v-model="explainWarn.different" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('wave')}}</view>
						<input type="digit" v-model="explainWarn.wave" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('subscript')}}</view>
						<input v-model="explainWarn.valueSubscript" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('remark')}}</view>
						<input v-model="explainWarn.remark" />
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('only')+$t('once')}}</view>
						<radio :class="[themeConfig.theme,explainWarn.onlyOnce ?'checked':'']"
							:checked="explainWarn.onlyOnce?true:false" :value="true"></radio>
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('startDate')}}</view>
						<picker mode="time" :value="explainWarn.dayStartTime" @change='startDateChange'>
							<view>{{explainWarn.dayStartTime || '00:00'}}</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">{{$t('endDate')}}</view>
						<picker mode="time" :value="explainWarn.dayEndTime" @change='endDateChange'>
							<view>{{explainWarn.dayEndTime || '00:00'}}</view>
						</picker>
					</view>

					<view class="cu-form-group" style="min-height:30rpx;">
					</view>
					<view class="flex justify-between align-center">
						<button class="cu-btn block line-grey margin lg" form-type="submit">{{$t('confirm')}}</button>
						<button class="cu-btn block line-grey margin lg"
							@tap="cancelExplainWarn">{{$t('cancel')}}</button>
					</view>
				</form>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showToast,
		showLoading,
		hideLoading
	} from '@/util/toast.js'
	import * as deviceSensorExplainApi from '@/api/iot/iotDeviceExplainApi.js'
	import Line from '@/components/UniChars/Line.vue'
	import {
		formatSensorType
	} from '@/util/dataUtil.js'
	import * as storage from '@/util/storage.js'
	import {
		formatDateTime
	} from '@/util/formatTime.js'
	export default {
		name: 'Explain',
		props: {
			sensor: {
				type: Object,
				default: () => {
					return {}
				}
			},
			deviceCore: {
				type: String,
				default: null
			},
			deviceName: {
				type: String,
				default: null
			}
		},
		components: {
			Line
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		data() {
			return {
				historyModalVisible: false,
				explain: {},
				explainWarnList: [],
				explainWarn: {},
				checkWarnList: [],
				isShowCheck: false,
				isShowWarnListModel: false,
				isShowEditWarnModel: false,
				explainChart: null,
				chartData: {
					categories: ['2016', '2017', '2018', '2019', '2020', '2021'],
					dataZoom: [{
							type: 'inside',
							start: 0,
							end: 100,
						},
						{
							start: 0,
							end: 100,
							top: '84%',
							handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
							handleSize: '80%',
							handleStyle: {
								color: '#fff',
								shadowBlur: 3,
								shadowColor: 'rgba(0, 0, 0.3, 0.6)',
								shadowOffsetX: 2,
								shadowOffsetY: 2
							}
						}
					],
					series: [{
						name: '目标值',
						data: [35, 36, 31, 33, 13, 34]
					}, {
						name: '完成量',
						data: [18, 27, 21, 24, 6, 28]
					}]
				},
				enableEval: storage.getEnableEval()
			}
		},
		methods: {
			formatDateTime(time) {
				return formatDateTime(time, this.$t('unKnow'))
			},
			formatValue(item) {
				if (this.enableEval) {
					switch (item.type) {
						case 'line:multi':
						case 'string:multi':
						case 'static:multi':
						case 'number:multi':
							return item.value
						default:
							if (null !== item.value) {
								return [item.value]
							} else {
								return []
							}
					}
				}
				return [item.rawValue]
			},
			formatSensorType(type) {
				return formatSensorType(this, type)
			},
			endDateChange(e) {
				this.explainWarn.dayEndTime = e.detail.value
			},
			startDateChange(e) {
				this.explainWarn.dayStartTime = e.detail.value
			},
			tapSensor(e) {
				const {
					sensorId,
					sensorName,
					port
				} = e
				uni.navigateTo({
					url: `/pages/deviceSensorData/deviceSensorData?sensorId=${sensorId}&sensorName=${sensorName}&deviceCore=${this.deviceCore}&deviceName=${this.deviceName}&port=${port}`
				})
			},
			formaterTime(createdTime) {
				const newDate = new Date();
				newDate.setTime(createdTime * 1000);
				return (newDate.getMonth() + 1) + '/' + newDate.getDate() + ' ' + newDate
					.getHours() + ':' + newDate.getMinutes()
			},
			getExplainDataList(explain) {
				this.explain = explain
				showLoading(this.$t('loading'), false)
				const time = new Date()
				this.startTimestamp = time.setTime(time.getTime() / 1000 - 7 * 24 * 60 * 60).toString();
				this.endTimestamp = Math.round(new Date().getTime() / 1000).toString();
				deviceSensorExplainApi.getExplainDataList({
					explainId: explain.explainId,
					startTime: this.startTimestamp,
					endTime: this.endTimestamp,
				}).then(res => {
					const {
						data
					} = res
					if (data) {
						const dataList = []
						for (let j = 0; j < data.length; j++) {
							const dataItem = data[j]
							dataList.push({
								time: this.formaterTime(dataItem.createdTime),
								val: dataItem.val,
							});

						}
						const item = {
							...explain
						};
						item.dataList = dataList;
						if (this.enableEval && (explain.type === 'line' || explain.type === 'number')) {
							item.showType = 'echarts'
						} else {
							item.showType = 'string'
						}
						if (item.dataList.length === 0) {
							dataList.push({
								time: this.formaterTime(explain.valueDate),
								val: explain.value,
							});
						}
						this.explainChart = item
						this.historyModalVisible = true
					}
					hideLoading()
				})
			},
			hideModal() {
				this.historyModalVisible = false
			},
			showCheck() {
				this.isShowCheck = true
			},
			changeCheck(e) {
				this.checkWarnList = e.detail.value
			},
			deleteExplainWarn() {
				const list = this.checkWarnList
				const explainWarnList = this.explainWarnList.filter((value, index) => {
					return list.indexOf(index + '') === -1
				});
				this.explainWarnList = explainWarnList
				this.getDeleteAndInsertList()

			},
			showAddWarnModel() {
				this.isShowEditWarnModel = true
				this.isShowWarnListModel = false
				this.explainWarn = {}
			},
			editExplainWarn(item) {
				this.isShowEditWarnModel = true
				this.isShowWarnListModel = false
				this.explainWarn = item
			},
			addOrUpdateExplainWarn(e) {
				const explainWarnList = this.explainWarnList
				if (this.explainWarn.warnId) {
					for (let i in this.explainWarnList) {
						const item = this.explainWarnList[i]
						if (item.warnId === this.explainWarn.warnId) {
							this.explainWarnList.splice(i, 1, this.explainWarn)
						}
					}
				} else {
					this.explainWarnList.unshift(this.explainWarn)
				}
				this.getDeleteAndInsertList()
				this.cancelExplainWarn()
			},
			getDeleteAndInsertList() {
				const explainWarnList = []
				for (const item of this.explainWarnList) {
					item.checked = false
					const dayStartTimeList = item.dayStartTime.split(':')
					const dayEndTimeList = item.dayEndTime.split(':')
					if (dayStartTimeList.length === 2) {
						item.dayStartTime = item.dayStartTime + ':00'
					}
					if (dayEndTimeList.length === 2) {
						item.dayEndTime = item.dayEndTime + ':00'
					}
					explainWarnList.push(item)
				}
				deviceSensorExplainApi.getDeleteAndInsertList({
					explainId: this.explain.explainId,
					warnList: explainWarnList
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						thidatahowToast(this.$t('success'), 'none', 1000, false)
					} else {
						showToast(this.$t('failure'), 'none', 1000, false)
					}
				})
			},
			showExplainWarn() {
				this.isShowWarnListModel = true
			},
			cancelExplainWarn() {
				if (this.isShowCheck) {
					this.isShowCheck = false
				} else if (this.isShowEditWarnModel) {
					this.isShowEditWarnModel = false
				} else {
					this.unShowExplainWarn()
				}
			},
			unShowExplainWarn() {
				this.isShowWarnListModel = false
			},
			getExplainWarnList(item) {
				this.explain = item
				const isShowWarnListModel = this.isShowWarnListModel
				deviceSensorExplainApi.getExplainWarnList({
					explainId: item.explainId
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						const explainWarnList = []
						for (const item of data) {
							item.checked = false
							const dayStartTimeList = item.dayStartTime.split(':')
							const dayEndTimeList = item.dayEndTime.split(':')
							if (dayStartTimeList.length > 2) {
								item.dayStartTime = dayStartTimeList[0] + ':' + dayStartTimeList[1]
							}
							if (dayEndTimeList.length > 2) {
								item.dayEndTime = dayEndTimeList[0] + ':' + dayEndTimeList[1]
							}
							explainWarnList.push(item)
						}
						this.explainWarnList = explainWarnList
						if (!isShowWarnListModel) {
							this.showExplainWarn()
						}
					}
				})
			},
			saveExplainWarn() {
				this.getDeleteAndInsertList(this.explainWarnList)
				this.unShowExplainWarn()
			},

		}
	}
</script>
<style>
	/* 	.input {
		border: 1rpx solid rgba(0, 0, 0, 0.1);
		border-radius: 5px;
		height: 80rpx;
		line-height: 80rpx;
	} */

	/* 	.ztnCustom-cur {
		transition: all .6s ease-in-out 0s;
		transform: translateX(0rpx)
	} */

	/* 	.ztnCustom-move-cur {
		transform: translateX(20%)
	}

	.ztnCustom-move {
		position: absolute;
		z-index: 999;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 20%;
		transform: translateX(-100%);
	}
 */
	/* .ztnCustom-realTime:last-child {
		margin-bottom: 150rpx
	} */
</style>
